//
//  MessageCircleFlowLayout.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/2/24.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit

class MessageCircleFlowLayout: UICollectionViewFlowLayout {
    var allAttributes: [UICollectionViewLayoutAttributes] = []
    let itemCountPerRow = 4
    let rowCount = 2
    override func prepare() {
        super.prepare()
        allAttributes.removeAll()
        let count = self.collectionView?.numberOfItems(inSection: 0)
        if let tureCount = count {
            for index in 0..<tureCount {
                let indexPath = IndexPath(item: index, section: 0)
                let attributes = self.layoutAttributesForItem(at: indexPath)
                allAttributes.append(attributes!)
            }
        }
    }
    
    override var collectionViewContentSize: CGSize {
        return super.collectionViewContentSize
    }
    
    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        let item = indexPath.item
        super.layoutAttributesForItem(at: indexPath)
        var x: Int = 0, y: Int = 0
        self.targetPositionWithItem(item: item, x: &x, y: &y)
        let item2 = self.originItem(x: x, y: y)
        let theNewIndexPath = IndexPath(item: item2, section: indexPath.section)
        let theNewAttr = super.layoutAttributesForItem(at: theNewIndexPath)
        theNewAttr?.indexPath = indexPath
        return theNewAttr
    }
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        let attributs = super.layoutAttributesForElements(in: rect)
        var tmp: [UICollectionViewLayoutAttributes] = []
        for attr in attributs! {
            for attr2 in self.allAttributes {
                if attr.indexPath.item == attr2.indexPath.item {
                    tmp.append(attr2)
                    break
                }
            }
        }
        return tmp
    }
    
    func targetPositionWithItem(item: NSInteger, x: inout NSInteger, y: inout NSInteger) {
        let page = item / (self.itemCountPerRow * self.rowCount)
        let theX = item % self.itemCountPerRow + page * self.itemCountPerRow
        let theY = item / self.itemCountPerRow - page * self.rowCount
        x = theX
        
        y = theY
    }
    
    func originItem(x: NSInteger, y: NSInteger) -> NSInteger {
        let item = x * self.rowCount + y
        return item
    }
}
